package com.aiwiown.snackmq.console.web;

import com.aiwiown.snackmq.common.auth.Action;
import com.aiwiown.snackmq.common.auth.Permission;
import com.aiwiown.snackmq.console.service.SnackMQAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Collections;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/permissions")
public class PermissionController {

    @Autowired
    private SnackMQAdminService adminService;
    @GetMapping
    public String permissionPage(Model model) {
        try {
            model.addAttribute("users", adminService.listUsers());
            model.addAttribute("roles", adminService.listRoles());
            // 【新增】为创建角色表单提供 Action 枚举的所有值
            model.addAttribute("actions", Action.values());
        } catch (Exception e) {
            model.addAttribute("error", "Failed to fetch permission data: " + e.getMessage());
        }
        return "permissions"; // 对应 permissions.html
    }

    /**
     * 【新增】处理创建用户的表单提交。
     */
    @PostMapping("/users/create")
    public String createUser(@RequestParam String username,
                             @RequestParam String password,
                             @RequestParam(required = false) List<String> roles,
                             RedirectAttributes redirectAttributes) {
        try {
            adminService.createUser(username, password, roles);
            redirectAttributes.addFlashAttribute("successMessage", "User '" + username + "' created successfully.");
        } catch (Exception e) {
            log.error("Failed to create user '{}'", username, e);
            redirectAttributes.addFlashAttribute("errorMessage", "Failed to create user: " + e.getMessage());
        }
        return "redirect:/permissions";
    }

    /**
     * 【新增】处理创建/更新角色的表单提交。
     */
    @PostMapping("/roles/create")
    public String createRole(@RequestParam String roleName,
                             @RequestParam Action action,
                             @RequestParam String resourceType,
                             @RequestParam String resourceName,
                             RedirectAttributes redirectAttributes) {
        try {
            // 简单起见，本次只支持创建一个带单条权限的角色
            Permission permission = new Permission(resourceType, resourceName, action);
            adminService.setRolePermissions(roleName, Collections.singletonList(permission));
            redirectAttributes.addFlashAttribute("successMessage", "Role '" + roleName + "' created/updated successfully.");
        } catch (Exception e) {
            log.error("Failed to create role '{}'", roleName, e);
            redirectAttributes.addFlashAttribute("errorMessage", "Failed to create role: " + e.getMessage());
        }
        return "redirect:/permissions";
    }

    /**
     * 【新增】处理删除用户的表单提交。
     */
    @PostMapping("/users/delete")
    public String deleteUser(@RequestParam String username, RedirectAttributes redirectAttributes) {
        try {
            adminService.deleteUser(username);
            redirectAttributes.addFlashAttribute("successMessage", "User '" + username + "' deleted successfully.");
        } catch (Exception e) {
            log.error("Failed to delete user '{}'", username, e);
            redirectAttributes.addFlashAttribute("errorMessage", "Failed to delete user: " + e.getMessage());
        }
        return "redirect:/permissions";
    }

    /**
     * 【新增】处理删除角色的表单提交。
     */
    @PostMapping("/roles/delete")
    public String deleteRole(@RequestParam String roleName, RedirectAttributes redirectAttributes) {
        try {
            adminService.deleteRole(roleName);
            redirectAttributes.addFlashAttribute("successMessage", "Role '" + roleName + "' deleted successfully.");
        } catch (Exception e) {
            log.error("Failed to delete role '{}'", roleName, e);
            redirectAttributes.addFlashAttribute("errorMessage", "Failed to delete role: " + e.getMessage());
        }
        return "redirect:/permissions";
    }
}